import axios from 'axios';
import { Modal } from 'antd';
import { getServer } from 'utils/share';
import { server } from 'configs';
import cookie from 'js-cookie';

let hasErrorModal = false;

const getBaseConfigs = () => {
  const token = cookie.get('token');
  const tokenType = cookie.get('tokenType');
  return {
    headers: {
      "Authorization":`${tokenType} ${token}`
    }
  };
};

const handleResponse = ({ data }) => {
  if(data && data.status === 200){
    return data;
  } else {
    if(!hasErrorModal){
      Modal.error({ 
        title: data.msg || '请求失败',
        onOk() {
          hasErrorModal = false;
          // if(data.status === 300){
          //   window.location.hash = '/login';
          // }
        }
      }); 
      hasErrorModal = true;
      return false;
    }
  }

};
// 
const handleError = (error) => {
  
  let ignoreTips = false;
  let msg = '请求失败';
  const errorResponse = error.response || {};
  // console.log(error.response, error.request);
  const config = error.config || {};
  const params = config.params || {};
  if(params.ignoreTips){
    ignoreTips = params.ignoreTips;
  }
  const errorResponseData = errorResponse.data || {};
  
  if(errorResponseData.message){
    msg = errorResponseData.message;
  }
  if(!error.response){
    msg = '网络连接错误，请稍后再试';
  }
  if(!ignoreTips && !hasErrorModal){
    Modal.error({ 
      title: msg,
      onOk() {
        hasErrorModal = false;
      }
    });
    hasErrorModal = true;
  }
  // console.log(Promise.resolve(error));
  return Promise.reject(error);
};

 // 请求结果处理
 const handleResult = (requestPromise) => {
  return requestPromise
  .then((data) =>  {
    return handleResponse(data);
  })
  .catch((error, data) => {
    return handleError(error);
  });
};



const http = (type) => {
  const instance = axios.create({
    // withCredentials: true,
    baseURL: getServer(server)[type],
    timeout: 8000
  });
  
  // get 请求
  const get = (url, params) => {
    const baseConfigs = getBaseConfigs();
    return handleResult(instance.get(url, {
      ...baseConfigs,
      params
    }));
  };

  // delete 请求
  const del = (url, params) => {
    const baseConfigs = getBaseConfigs();
    return handleResult(instance.delete(url, {
      ...baseConfigs,
      params
    }));
  };
  // post 请求
  const post = (url, params) =>{
    const baseConfigs = getBaseConfigs();
    return handleResult(instance.post(url, params, { ...baseConfigs }));
  }; 
  // put 请求
  const put = (url, params) =>{
    const baseConfigs = getBaseConfigs();
    return handleResult(instance.put(url, params, { ...baseConfigs }));
  }; 
  return {
    get,
    post,
    del,
    put
  };
};
export default http;

